<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: GetCart.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\duobao;

use app\api\model\dao\DuoBaoCart;
use app\api\model\dao\Goods;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use think\Cache;

class GetDuoBaoCart extends PageBase
{

    private $objDuoBaoCart;
    private $objGoods;

    public function __construct()
    {
        parent::__construct();
        $this->objDuoBaoCart = new DuoBaoCart();
        $this->objGoods = new Goods();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'user_id' => 'require',
        ];
        $msg = [
            'user_id.require' => '用户ID必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        //if (false === $ret) {
        //    return $this->getRes(Error::ERR_NO_AUTH);
        //}

        // 获取订单信息
        $arrCond = array();
        $arrCond['user_id'] = !empty($this->user_id) ? $this->user_id : 0;

        $perpage = isset($param['perpage']) ? intval($param['perpage']) : 0;
        $page = isset($param['page']) ? intval($param['page']) : 0;
        $perpage = max(10, $perpage);
        $page = max(1, $page);
        $offset = ($page - 1) * $perpage;
        $limit = $perpage;


        $counts = $this->objDuoBaoCart->getCount($arrCond);
        $rets = $this->objDuoBaoCart->getDuoBaoCartByCond($arrCond, [], $offset, $limit, ' goods_id desc ');

        if ($rets === false) {
            return $this->getRes(Error::ERR_SYS);
        }

        // 获取商品信息
        $goods_arr = [];
        $goods_ids = array_map(function ($v) {
            return $v['goods_id'];
        }, $rets);
        $goods = $this->objGoods->getGoods(implode(',', $goods_ids));
        foreach ($goods as $good) {
            $goods_arr[$good['goods_id']] = $good;
        }

        foreach ($rets as &$v) {
            if (isset($goods_arr[$v['goods_id']])) {
                $v['goods_thumb'] = $goods_arr[$v['goods_id']]['goods_thumb'];
            }
        }

        $this->data = array(
            'list' => $rets,
            'total' => $counts,
        );

        return $this->getRes();
    }
}
